package com.itboye.ihomebank;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.mobileim.lib.model.message.IFileMessage;
import com.itboye.ihomebank.activity.home.ActivitySwitchRoles;
import com.itboye.ihomebank.activity.key.ActivitySheBei;
import com.itboye.ihomebank.activity.key.UpdateKeyActivity;
import com.itboye.ihomebank.activity.keytwo.KeyGuanLiActivity;
import com.itboye.ihomebank.activity.keytwo.KeyZuHuActivity;
import com.itboye.ihomebank.activity.keytwo.SheBeiTwoActivity;
import com.itboye.ihomebank.activity.keytwo.UpdateKeyTwoActivity;
import com.itboye.ihomebank.activity.login.LoginActivity;
import com.itboye.ihomebank.activity.login.WelcomeActivity;
import com.itboye.ihomebank.activity.me.ActivityMyData;
import com.itboye.ihomebank.activity.me.ActivitySetting;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.ConfigBean;
import com.itboye.ihomebank.bean.MessWeiDuBean;
import com.itboye.ihomebank.bean.PersonDataBean;
import com.itboye.ihomebank.bean.RedDotBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.UpdateVersionBean;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.HousePresenter;
import com.itboye.ihomebank.presenter.KeyPresenter;
import com.itboye.ihomebank.presenter.UpdatePresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.ttKey.DaoMaster;
import com.itboye.ihomebank.ttKey.DaoSession;
import com.itboye.ihomebank.ttKey.DbService;
import com.itboye.ihomebank.ttKey.Key;
import com.itboye.ihomebank.ttKey.KeyDao;
import com.itboye.ihomebank.ttKey.MyPreference;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.ListDialog;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.SavePersonData;
import com.itboye.ihomebank.util.UIAlertView;
import com.itboye.ihomebank.util.UpdateManager;
import com.itboye.ihomebank.util.broad.BroadEnum;
import com.itboye.ihomebank.util.broad.RedDotEnum;
import com.itboye.ihomebank.util.controller.LoginController;
import com.itboye.ihomebank.util.controller.LoginedState;
import com.itboye.ihomebank.util.controller.UnLoginState;
import com.itboye.ihomebank.zjtlcb.lnd.livenessdetector.activity.MainLiveActivity;
import com.sitri.sdk.SLock;
import com.sitri.sdk.callback.visible.CommonCallback;
import com.sitri.sdk.model.ID;
import com.sitri.sdk.model.ResultData;
import com.sitri.sdk.model.ResultError;

import org.greenrobot.greendao.database.Database;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import static com.itboye.ihomebank.base.MyApplcation.getStringContent;

/**
 * 项目的主Activity，所有的Fragment都嵌入在这里。
 * @author guolin
 */
@SuppressLint("ResourceAsColor")
public class MainActivity extends BaseOtherActivity implements OnClickListener,
		Observer , CommonCallback {
	//用于展示消息的Fragment
	private HomeFragment messageFragment;
	//消息的Fragment
	private MessageFragment contactsFragment;
	// 用于展示动态的Fragment
	private ServiceFragment newsFragment;
	//用于展示设置的Fragment
	private MeFragment settingFragment;
	//钥匙的Fragment
	private KeyFragment keyFragment;
	//消息界面布局
	private View messageLayout,contactsLayout,newsLayout,settingLayout;
	//钥匙
	RelativeLayout key_layout;
	//在Tab布局上显示的控件
	private ImageView messageImage,contactsImage,newsImage,settingImage;
	//在Tab布局上显示的控件
	private TextView messageText,contactsText,newsText,settingText;
	private LinearLayout main_ll;

	//用于对Fragment进行管理
	public static int WIDTH;
	private FragmentManager fragmentManager;
	ImageView key_image,
			mess_img,wode_img,home_img;//红点
	UserPresenter presenter;
	KeyPresenter keyPresenter;
	String uid;
	String mac;//绑定的科技侠mac地址(如果存在代表虽然绑定了锁，但是没有上传到我们的服务器)
	String baima_mac;//绑定的白马mac地址(如果存在代表虽然绑定了锁，但是没有上传到我们的服务器)
	int dian = 0;
	public static MainActivity act;
	private long touchTime = 0;
	private long waitTime = 2000;
    int activityType=0;// 1 是从闪屏调过来的（首次启动）
	private BluetoothAdapter bluetoothAdapter;

	private UIAlertView uiAlertView;
	HousePresenter mHousePresenter;
	UpdatePresenter updatePresenter;

    public static int BROKER_VALIDATE=0;//默认是普通用户

	boolean isClick=false;//是否在连续点击 （切换到mefragment时用）
	String actionName ="";
	public static MainActivity onSetFragment() {
		return act;
	}
	public static boolean isLock=false;
	/**
	 * 在这里获取到每个需要用到的控件的实例，并给它们设置好必要的点击事件。
	 */
	private void initViews() {

//		if (getIntent().getStringExtra("type")!=null){//纯锁模式下 顶部状态栏发生改变
//			main_ll.setFitsSystemWindows(false);
//			isLock=true;
//
//
//		}else { //非纯门锁
//			isLock=false;
//			main_ll.setFitsSystemWindows(true);
//			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//				getWindow().setStatusBarColor(getResources().getColor(R.color.home_blue));
//			}
//		}
//		setStatusBarColor(getResources().getColor(R.color.title_blue));
        //是否弹出弹框
		activityType=getIntent().getIntExtra("Tankuang",0);
		mHousePresenter=new HousePresenter(this);
		presenter = new UserPresenter(this);
		keyPresenter = new KeyPresenter(this);
		presenter.getConfig();

		if (activityType==1){
			activityType=0;
			if (!"".equals(SPUtils.get(this.getApplication(),null,SPContants.USER_ID,"")+"")){
				mHousePresenter.queryRedDot(SPUtils.get(this.getApplication(),null,SPContants.USER_ID,"")+"",MyApplcation.device_token);
			}

		}else {
			updateRedDot(wode_img, (Boolean) SPUtils.get(getApplication(),null,SPContants.FUJIAN_ORDER,false));
			updateRedDot(home_img, (Boolean) SPUtils.get(getApplication(),null,SPContants.FUJIAN_ORDER,false));
		}

		init();

		//退出登录发送过来的广播
		IntentFilter filter1 = new IntentFilter(ActivityMyData.AVARTACTION);
		registerReceiver(loginReceiver, filter1);
		//登录的广播
		IntentFilter filter2 = new IntentFilter("changeavart");
		registerReceiver(loginReceiver, filter2);
		//房东刚确认合同后
		IntentFilter filter3 =new IntentFilter("showRedDot");
		registerReceiver(loginReceiver,filter3);

		// 有新的消息
		IntentFilter filter_mess = new IntentFilter("mess_new");
		registerReceiver(messReceiver, filter_mess);


		SLock.getServices().setIsDebug(true);
		SLock.getServices().setCommonCallback(this);

	}
	BroadcastReceiver xiaoxia_receiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			setTabSelection(1);
		};
	};
	BroadcastReceiver loginReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			uid = (String) SPUtils.get(MyApplcation.ctx, null, SPContants.USER_ID, "");
			mac= (String) SPUtils.get(MyApplcation.ctx, null, SPContants.LOCKMAC, "");
			baima_mac= (String) SPUtils.get(MyApplcation.ctx, null, SPContants.BAIMA_LOCKMAC, "");

			if (!uid.equals("")){
				SLock.getServices().login(uid, "itboye");
			}
			if ((Boolean) SPUtils.get(MyApplcation.ctx, null,
					SPContants.MESS_NEW, false)) {
				mess_img.setVisibility(View.VISIBLE);
			} else {
				mess_img.setVisibility(View.GONE);
			}
			if (intent.getAction().equals(ActivityMyData.AVARTACTION)){//退出登录
				actionName=intent.getAction();
				home_img.setVisibility(View.GONE);
				wode_img.setVisibility(View.GONE);
				if (contactsFragment!=null){
					contactsFragment.hideRedDot();
				}
			}else if (intent.getAction().equals("changeavart")||intent.getAction().equals("showRedDot")){//登录
				actionName=intent.getAction();
				mHousePresenter.queryRedDot(uid,MyApplcation.device_token);

			}

		};
	};
	BroadcastReceiver messReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			if ((Boolean) SPUtils.get(MyApplcation.ctx, null,
					SPContants.MESS_NEW, false)) {
				mess_img.setVisibility(View.VISIBLE);
			} else {
				mess_img.setVisibility(View.GONE);
			}
		};
	};

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		UpdateVersionBean updateVersionBean = new UpdateVersionBean();
		updatePresenter.Update(updateVersionBean);
		if (keyFragment!=null){
			//刷新列表
			if ( !SPUtils.get(MyApplcation.ctx, null, SPContants.USER_ID, "").equals("")){
				keyFragment.refreshList();
			}

		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(loginReceiver);
		unregisterReceiver(messReceiver);
		unregisterReceiver(xiaoxia_receiver);
	}

	private void init(){
		messageLayout = findViewById(R.id.message_layout);
		contactsLayout = findViewById(R.id.contacts_layout);
		newsLayout = findViewById(R.id.news_layout);
		settingLayout = findViewById(R.id.setting_layout);
		messageImage = (ImageView) findViewById(R.id.message_image);
		contactsImage = (ImageView) findViewById(R.id.contacts_image);
		newsImage = (ImageView) findViewById(R.id.news_image);
		settingImage = (ImageView) findViewById(R.id.setting_image);
		messageText = (TextView) findViewById(R.id.message_text);
		contactsText = (TextView) findViewById(R.id.contacts_text);
		newsText = (TextView) findViewById(R.id.news_text);
		settingText = (TextView) findViewById(R.id.setting_text);
		home_img= (ImageView) findViewById(R.id.home_img);
		wode_img= (ImageView) findViewById(R.id.wode_img);

		messageLayout.setOnClickListener(this);
		contactsLayout.setOnClickListener(this);
		newsLayout.setOnClickListener(this);
		settingLayout.setOnClickListener(this);

//		SPUtils.put(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"DAF");
//        SPUtils.put(MyApplcation.ctx,null,SPContants.ISLOCK,true);
		uid = (String) SPUtils.get(MyApplcation.ctx, null, SPContants.USER_ID, "");
		mac= (String) SPUtils.get(MyApplcation.ctx, null, SPContants.LOCKMAC, "");
		baima_mac= (String) SPUtils.get(MyApplcation.ctx, null, SPContants.BAIMA_LOCKMAC, "");

		/**
		 * 登录状态
		 */
		if ((Boolean) SPUtils.get(MyApplcation.ctx, null,
				SPContants.IS_LOGINED, false)) {
			LoginController.setLoginState(new LoginedState());
			SLock.getServices().login(uid, "itboye");
			keyPresenter.onJudge(uid);	//判断是否注册了白马云锁
			Log.v("logined", "已经登录");
		} else {
			LoginController.setLoginState(new UnLoginState());
			Log.v("logined", "未登录");
		}

		if ((Boolean) SPUtils.get(MyApplcation.ctx, null,
				SPContants.MESS_NEW, false)) {
			mess_img.setVisibility(View.VISIBLE);
		} else {
			if(uid==null||uid.equals("")){//uid为空的时候跳转到登陆
				return;
			}
			keyPresenter.getWeiDu(uid);
		}
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.message_layout:
			isClick=false;
			dian = 0;
			// 当点击了消息tab时，选中第1个tab
			setTabSelection(0);
			break;
		case R.id.contacts_layout:
			isClick=false;
			dian = 0;
			// 当点击了联系人tab时，选中第2个tab
			setTabSelection(1);
			break;
		case R.id.key_image:// 当点击了动态tab时，选中第3个tab
			isClick=false;
			if(uid==null||uid.equals("")){//uid为空的时候跳转到登陆
				Intent intent=new Intent(this,LoginActivity.class);
				startActivity(intent);
				return;
			}
			if(!mac.equals("")){
				Intent intent=new Intent(this,UpdateKeyActivity.class);
				startActivity(intent);
				return;
			}
			if(!baima_mac.equals("")){
				Intent intent=new Intent(this,UpdateKeyTwoActivity.class);
				startActivity(intent);
				return;
			}
			dian++;
			if (dian > 1) {
				if (KeyFragment.clockProduct%2==1){//科技侠
					Intent intent = new Intent(MainActivity.this, ActivitySheBei.class);
					startActivity(intent);
				}else {
					Intent intent = new Intent(MainActivity.this, SheBeiTwoActivity.class);
					startActivity(intent);
				}

			}
			setTabSelection(2);
			break;
		case R.id.news_layout:
			dian = 0;
			isClick=false;
			// 当点击了设置tab时，选中第4个tab
			setTabSelection(3);
			break;
		case R.id.setting_layout:

			dian = 0;
			setTabSelection(4);
			break;

		default:
			break;
		}
	}

	/**
	 * 根据传入的index参数来设置选中的tab页。
	 * @param index  每个tab页对应的下标。0表示消息，1表示联系人，2表示动态，3表示设置。
	 */
	@SuppressLint("ResourceAsColor")
	public void setTabSelection(int index) {
		// 每次选中之前先清楚掉上次的选中状态
		clearSelection();
		// 开启一个Fragment事务
		FragmentTransaction transaction = fragmentManager.beginTransaction();
		// 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
		hideFragments(transaction);
		switch (index) {
		case 0:
			dian = 0;
			// 当点击了首页tab时，改变控件的图片和文字颜色
			messageImage.setImageResource(R.drawable.shouye_blue);
			messageText
					.setTextColor(Color.parseColor("#74C6BE"));
			if (messageFragment == null) {
				// 如果MessageFragment为空，则创建一个并添加到界面上
				messageFragment = new HomeFragment();
				transaction.add(R.id.content, messageFragment);
			} else {
				// 如果MessageFragment不为空，则直接将它显示出来
				transaction.show(messageFragment);
			}
			break;
		case 1:
			dian = 0;
			// 当点击了消息tab时，改变控件的图片和文字颜色
			contactsImage.setImageResource(R.drawable.xiaoxi_blue);
			contactsText.setTextColor(Color.parseColor("#74C6BE"));
			if (contactsFragment == null) {
				// 如果ContactsFragment为空，则创建一个并添加到界面上
				contactsFragment = new MessageFragment();
				transaction.add(R.id.content, contactsFragment);
			} else {
				// 如果ContactsFragment不为空，则直接将它显示出来
				transaction.show(contactsFragment);
			}
			break;
		case 2:

			// 当点击了我的tab时，改变控件的图片和文字颜色
			key_image.setImageResource(R.drawable.tianjiashebei);

			if (keyFragment == null) {
				// 如果SettingFragment为空，则创建一个并添加到界面上
				keyFragment = new KeyFragment();
				transaction.add(R.id.content, keyFragment);
			} else {
				// 如果SettingFragment不为空，则直接将它显示出来
				transaction.show(keyFragment);
			}
			break;
		case 3:
			dian = 0;
			// 当点击了服务tab时，改变控件的图片和文字颜色
			newsImage.setImageResource(R.drawable.shenghuo_blue);
			newsText.setTextColor(Color.parseColor("#74C6BE"));
			if (newsFragment == null) {
				// 如果NewsFragment为空，则创建一个并添加到界面上
				newsFragment = new ServiceFragment();
				transaction.add(R.id.content, newsFragment);
			} else {
				// 如果NewsFragment不为空，则直接将它显示出来
				transaction.show(newsFragment);
			}

			break;
		case 4:
			dian = 0;
			// 当点击了我的tab时，改变控件的图片和文字颜色
			settingImage.setImageResource(R.drawable.wode_blue);
			settingText
					.setTextColor(Color.parseColor("#74C6BE"));
			if (settingFragment == null) {
				// 如果SettingFragment为空，则创建一个并添加到界面上
				settingFragment = new MeFragment();
				transaction.add(R.id.content, settingFragment);
			} else {
				// 如果SettingFragment不为空，则直接将它显示出来
				transaction.show(settingFragment);
			}
			break;
		default:

			break;
		}
		transaction.commit();
	}

	/**
	 * 清除掉所有的选中状态。
	 */
	@SuppressLint("ResourceAsColor")
	private void clearSelection() {
		messageImage.setImageResource(R.drawable.shouye_black);
		messageText.setTextColor(getResources().getColor(R.color.black_1a));
		contactsImage.setImageResource(R.drawable.xiaoxi_black);
		contactsText.setTextColor(getResources().getColor(R.color.black_1a));
		newsImage.setImageResource(R.drawable.shenghuo_black);
		newsText.setTextColor(getResources().getColor(R.color.black_1a));
		settingImage.setImageResource(R.drawable.wode_black);
		settingText.setTextColor(getResources().getColor(R.color.black_1a));
		key_image.setImageResource(R.drawable.mensuo);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
	}

	/**
	 * 将所有的Fragment都置为隐藏状态。
	 * @param transaction 用于对Fragment执行操作的事务
	 */
	private void hideFragments(FragmentTransaction transaction) {
		if (messageFragment != null) {
			transaction.hide(messageFragment);
		}
		if (contactsFragment != null) {
			transaction.hide(contactsFragment);
		}
		if (keyFragment != null) {
			transaction.hide(keyFragment);
		}
		if (newsFragment != null) {
			transaction.hide(newsFragment);
		}
		if (settingFragment != null) {
			transaction.hide(settingFragment);
		}
	}

	@Override
	protected int layout_id() {
		// TODO Auto-generated method stub
		return R.layout.activity_main;
	}

	@Override
	protected void onInitController() {
		// TODO Auto-generated method stub
	}

	@Override
	protected void onInit() {
		// TODO Auto-generated method stub
	}

	@Override
	protected void onReadIntent(Bundle bundle) {
		// TODO Auto-generated method stub
	}

	@SuppressLint("ResourceAsColor")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
//		setStatusBarColor(R.color.text_gray);
		//沉浸式
		other();

//		SPUtils.put(MyApplcation.ctx,null,SPContants.ISLOCK,true);
//		SPUtils.put(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"123");
		initViews();
		act = this;
		fragmentManager = getSupportFragmentManager();
		//纯门锁模式下 钥匙为非正常状态下 如冻结等 跳转到锁列表界面
		String unlock = getIntent().getStringExtra("unlock");
		if (unlock!=null&&!unlock.equals("")){
			setTabSelection(2);
		}else {
			// 第一次启动时选中第0个tab
			setTabSelection(0);
		}
		WIDTH = getWindowManager().getDefaultDisplay().getWidth();
		bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		if (getIntent().getStringExtra("type")!=null){//纯锁模式下的点击消息
			if (getIntent().getStringExtra("type").equals("1")){
				setTabSelection(1);
			}
		}


		// 有新的消息
		IntentFilter xiaoxia = new IntentFilter("xiaoxia");
		registerReceiver(xiaoxia_receiver, xiaoxia);

		updatePresenter = new UpdatePresenter(this);
		UpdateVersionBean updateVersionBean = new UpdateVersionBean();
		updatePresenter.Update(updateVersionBean);

	}

	//更新弹框
	public void onManager(UpdateVersionBean appUpdateBean) {
		UpdateManager manager = new UpdateManager(this,
				appUpdateBean.getUpdate_log() + "",
				appUpdateBean.getDownload_url().get(0).getValue(),appUpdateBean.getVersion(),1);
		manager.checkUpdateInfo();
	}
	@Override
	public void update(Observable observable, Object data) {
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == UpdatePresenter.update_success) {
				UpdateVersionBean appUpdateBean = (UpdateVersionBean) entity.getData();
				String jgVersion = appUpdateBean.getVersion();
				int versionInt = Integer.parseInt(jgVersion.replace(".", ""));
				String oldVersion =getAppVersionName(this);
				int versionoldInt = Integer.parseInt(oldVersion.replace(".", ""));
				if (versionoldInt <versionInt){
					onManager(appUpdateBean);
				}else{
				}
			} else if (entity.getEventType() == UpdatePresenter.update_fail) {
				//  ByAlert.alert("更新解析失败");
			}
			if (entity.getEventType() == UserPresenter.getConfig_success) {
				ConfigBean beans = (ConfigBean) entity.getData();
				long shiqu = Long.parseLong(beans.getTimezoneRawOffset()) * 1000;
				SPUtils.put(MainActivity.this, null, SPContants.SHIQU, String.valueOf(shiqu));// 时区

				long ss = Long.parseLong(beans.getServerTime()) * 1000;
				long aa = System.currentTimeMillis();
				String shicha = String.valueOf(aa - ss);
				SPUtils.put(MainActivity.this,null,SPContants.oldPhoneTime,aa);
				SPUtils.put(MainActivity.this,null,SPContants.oldServiceTime,ss);

				SPUtils.put(MainActivity.this, null, SPContants.SHICHA, shicha);// 时差
			} else if (entity.getEventType() == UserPresenter.getConfig_fail) {
			} else if (entity.getEventType() == KeyPresenter.weidu_success) {
				MessWeiDuBean bean = (MessWeiDuBean) entity.getData();
				// 有新消息  发送广播
				if (bean.getSystem() > 0 || bean.getSign() > 0 || bean.getLock() > 0) {
					mess_img.setVisibility(View.VISIBLE);
					SPUtils.put(MainActivity.this, null,
							SPContants.MESS_NEW, true);
				} else {
					mess_img.setVisibility(View.GONE);
					SPUtils.put(MainActivity.this, null,
							SPContants.MESS_NEW, false);
				}
			} else if (entity.getEventType() == KeyPresenter.isregSitri_success) {//判断是否注册了白马云锁
				//	ByAlert.alert(entity.getData());
				if (entity.getData().equals("0")) {

					SLock.getServices().register(uid, "itboye");//注册到白马云锁
				}
			} else if (entity.getEventType() == KeyPresenter.isregSitri_fail) {
				//ByAlert.alert(entity.getData());
			} else if (entity.getEventType() == KeyPresenter.regSitri_success) {
				//ByAlert.alert(entity.getData());
			} else if (entity.getEventType() == KeyPresenter.regSitri_fail) {
				//ByAlert.alert(entity.getData());
			}else  if (entity.getEventType() == HousePresenter.queryRedDot_success){
				Log.d("main==","main_true");
				RedDotBean mRedDotBean= (RedDotBean) entity.getData();
				if (!actionName.equals("showRedDot")){
					showDialog(mRedDotBean);//展示所有弹框
				}else {

				}
				saveRedDotData(mRedDotBean);//保存红点数据
				if (contactsFragment!=null){
					contactsFragment.showRedDot();
				}
			}else if (entity.getEventType() == HousePresenter.queryRedDot_fail){
				if (entity.getCode().equals("-2")||entity.getMsg().equals("登录已失效，请重新登录")){
					ByAlert.alert("登录已失效，请重新登录");
					if(!uid.equals("")){
						exit();
					}
					startActivity(new Intent(this,LoginActivity.class));
				}
//                Log.d("hongdian=","false");
//                ByAlert.alert("");
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(event.getAction() == KeyEvent.ACTION_DOWN && KeyEvent.KEYCODE_BACK == keyCode) {
			long currentTime = System.currentTimeMillis();
			if((currentTime-touchTime)>=waitTime) {
				ByAlert.alert("再按一次退出");
				touchTime = currentTime;
			}else {
				finish();
				//退出后关闭进程
				//   android.os.Process.killProcess(android.os.Process.myPid());
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void finish() {
		super.finish();
		if (isTaskRoot()){
			if (bluetoothAdapter!=null){
				bluetoothAdapter.disable();//关闭蓝牙
			}
		}
	}

	@Override
	public void onSuccess(ResultData resultData) {
		log(resultData.getId(), true, resultData.getData());
		if (resultData.getId() == ID.REGISTER) {//白马锁注册成功之后登陆
			keyPresenter.regSitri(uid);//注册到后台
			SLock.getServices().login(uid, "itboye");
		}
	}

	@Override
	public void onFailed(ResultError resultError) {
		log(resultError.getId(), false, resultError.getErrorCode().toLog());
	}

	private String str = "";
	private void log(ID id, boolean isSuccess, String log) {
		str += getTime() + " " + id.name() + "：";
		if (isSuccess) {
			str += "Successful\n";
		} else {
			str += "Failed\n";
		}
		if (TextUtils.isEmpty(log)) {
			str += "\n";
		} else {
			str += log;
			str += "\n\n";
		}
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				//ByAlert.alert(str);
			}
		});
	}
	private String getTime() {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		return simpleDateFormat.format(new Date());
	}


	//显示dialog
	public  void showDialog(RedDotBean mRedDotBean){
		//dialog type  1  尚有租金逾期未交  2 尚有附件清单未确认 3 尚有未完成的签约 4 尚有申请签约的房源

		if (MyApplcation.mShenQin==null){
			//经纪人去选租客
			if (mRedDotBean.getApply_list().size()>0){

				MyApplcation.mShenQin= new ListDialog(
						MainActivity.this,
						"尚有申请签约的房源",
						mRedDotBean.getApply_list(),
						4);
				MyApplcation.mShenQin.getDialog_cancelImg().setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						MyApplcation.mShenQin.cancel();
						MyApplcation.mShenQin=null;
					}
				});
				if (mRedDotBean.getApply_list().size()>12){
					MyApplcation.mShenQin.setListDialogHeigh();
				}
				MyApplcation.mShenQin.show();
			}
		}

		if (MyApplcation.mQianDing==null){
			//租客签订合同
			if (mRedDotBean.getNeed_sign_contract_list().size()>0){
				MyApplcation.mQianDing= new ListDialog(
						MainActivity.this,
						"尚有未完成的签约",
						mRedDotBean.getNeed_sign_contract_list(),
						3);

				MyApplcation.mQianDing.getDialog_cancelImg().setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						MyApplcation.mQianDing.cancel();
						MyApplcation.mQianDing=null;
					}
				});
				if (mRedDotBean.getNeed_sign_contract_list().size()>12){
					MyApplcation.mQianDing.setListDialogHeigh();
				}
				MyApplcation.mQianDing.show();
			}
		}

		if (MyApplcation.mFujian==null){
			//租客确定附件单
			if (mRedDotBean.getNeed_confirm_facility_list().size()>0){
				List<String> confirm = new ArrayList<>();
				List<String> contract_no = new ArrayList<>();
				for (int i=0;i< mRedDotBean.getNeed_confirm_facility_list().size();i++){
					contract_no.add(mRedDotBean.getNeed_confirm_facility_list().get(i).getContract_no());
					confirm.add(getStringContent(mRedDotBean.getNeed_confirm_facility_list().get(i)));
				}
				MyApplcation.mFujian= new ListDialog(
						MainActivity.this,
						"尚有附件清单未确认",
						confirm,
						2,contract_no);
				MyApplcation.mFujian.getDialog_cancelImg().setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						MyApplcation.mFujian.cancel();
						MyApplcation.mFujian=null;
					}
				});
				if (mRedDotBean.getNeed_confirm_facility_list().size()>2){
					MyApplcation.mFujian.setListDialogHeigh();
				}
				MyApplcation.mFujian.show();
			}
		}
		if (MyApplcation.mYuQi==null){

			//租客逾期支付
			if (mRedDotBean.getOverdue_list().size()>0){
				MyApplcation.mYuQi= new ListDialog(
						MainActivity.this,
						"尚有租金逾期未交",
						mRedDotBean.getOverdue_list(),
						1);
				MyApplcation.mYuQi.getDialog_cancelImg().setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						MyApplcation.mYuQi.cancel();
						MyApplcation.mYuQi=null;
					}
				});
				if (mRedDotBean.getOverdue_list().size()>12){
					MyApplcation.mYuQi.setListDialogHeigh();
				}
				MyApplcation.mYuQi.show();
			}
		}







	}

	//存储红点
	public  void saveRedDotData(RedDotBean mRedDotBean) {
		if (mRedDotBean.getNeed_write_facility_count()>0){ //需要填写附件单的合同数
			SPUtils.put(MainActivity.this,null,SPContants.FUJIAN_ORDER,true);
			 //我的签约的红点
				home_img.setVisibility(View.VISIBLE);
//					 table_mess_img.setVisibility(View.VISIBLE);
				wode_img.setVisibility(View.VISIBLE);
		}else {
			home_img.setVisibility(View.GONE);
//					 table_mess_img.setVisibility(View.GONE);
			wode_img.setVisibility(View.GONE);
		}

		    SPUtils.put(MainActivity.this,null,SPContants.YUQI_COUNT,mRedDotBean.getOverdue_count());//逾期合同数
			SPUtils.put(MainActivity.this,null,SPContants.TOTAL_MESSAGE,mRedDotBean.getUnread_count().getTotal());//消息总数
		if (mRedDotBean.getUnread_count().getTotal()>0){
			mess_img.setVisibility(View.VISIBLE);
		}else {
			mess_img.setVisibility(View.GONE);
		}
			SPUtils.put(MainActivity.this,null,SPContants.SYSTEM_MESSAGE,mRedDotBean.getUnread_count().getSystem());//系统消息

		    SPUtils.put(MainActivity.this,null,SPContants.CONTRANCT_MESSAGE,mRedDotBean.getUnread_count().getContract());//签约消息
			SPUtils.put(MainActivity.this,null,SPContants.LOCK_MESSAGE,mRedDotBean.getUnread_count().getLock());//锁消息
			SPUtils.put(MainActivity.this,null,SPContants.REPAIR_COUNT,mRedDotBean.getRepair_count());//未维修数
			SPUtils.put(MainActivity.this,null,SPContants.BILL_COUNT,mRedDotBean.getBill_count());//账单数
		    sendBroadcast(new Intent("changeByMainActivity"));
	}

	//是否显示红点
	public void updateRedDot(ImageView imageView,boolean isTrue){

		if (isTrue){
			imageView.setVisibility(View.VISIBLE);
		}else {
			imageView.setVisibility(View.GONE);
		}
	}


}
